package tools

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"strconv"
	"strings"

	"anders-cli/internal/ai"
	"anders-cli/pkg/logger"
)

// registerCustomTools 注册自定义工具
func (tc *ToolCaller) registerCustomTools() {
	tc.availableTools["calculate"] = tc.calculateTool
	tc.availableTools["web_search"] = tc.webSearchTool
	logger.Info("已注册自定义工具: calculate, web_search")
}

// getCustomTools 获取自定义工具定义
func (tc *ToolCaller) getCustomTools() []ai.Tool {
	var tools []ai.Tool

	// 计算工具
	tools = append(tools, ai.Tool{
		Type: "function",
		Function: struct {
			Name        string                 `json:"name"`
			Description string                 `json:"description"`
			Parameters  map[string]interface{} `json:"parameters"`
		}{
			Name:        "calculate",
			Description: "执行数学计算表达式，支持基本的算术运算",
			Parameters: map[string]interface{}{
				"type": "object",
				"properties": map[string]interface{}{
					"expression": map[string]interface{}{
						"type":        "string",
						"description": "数学表达式，如 '2 + 3 * 4' 或 '(10 - 2) / 3'",
					},
				},
				"required": []string{"expression"},
			},
		},
	})

	// 网络搜索工具
	tools = append(tools, ai.Tool{
		Type: "function",
		Function: struct {
			Name        string                 `json:"name"`
			Description string                 `json:"description"`
			Parameters  map[string]interface{} `json:"parameters"`
		}{
			Name:        "web_search",
			Description: "在网络上搜索信息，返回相关结果",
			Parameters: map[string]interface{}{
				"type": "object",
				"properties": map[string]interface{}{
					"query": map[string]interface{}{
						"type":        "string",
						"description": "搜索关键词或短语",
					},
					"limit": map[string]interface{}{
						"type":        "integer",
						"description": "返回结果数量限制，默认为5",
						"default":     5,
					},
				},
				"required": []string{"query"},
			},
		},
	})

	return tools
}

// calculateTool 计算工具实现
func (tc *ToolCaller) calculateTool(args map[string]interface{}) (string, error) {
	expression, ok := args["expression"].(string)
	if !ok {
		return "", fmt.Errorf("缺少必需参数: expression")
	}

	logger.Info("执行计算: %s", expression)

	// 简单的数学表达式求值
	result, err := evaluateMathExpression(expression)
	if err != nil {
		logger.Warn("计算失败: %v", err)
		return "", fmt.Errorf("计算失败: %v", err)
	}

	response := fmt.Sprintf("计算结果: %s = %v", expression, result)
	logger.Info("计算完成: %s", response)

	return response, nil
}

// webSearchTool 网络搜索工具实现
func (tc *ToolCaller) webSearchTool(args map[string]interface{}) (string, error) {
	query, ok := args["query"].(string)
	if !ok {
		return "", fmt.Errorf("缺少必需参数: query")
	}

	limit := 5
	if limitVal, exists := args["limit"]; exists {
		if limitFloat, ok := limitVal.(float64); ok {
			limit = int(limitFloat)
		}
	}

	logger.Info("执行网络搜索: %s (限制: %d)", query, limit)

	// 使用 DuckDuckGo 搜索 API (免费且不需要API密钥)
	results, err := performDuckDuckGoSearch(query, limit)
	if err != nil {
		logger.Warn("网络搜索失败: %v", err)
		return "", fmt.Errorf("搜索失败: %v", err)
	}

	response := fmt.Sprintf("🔍 搜索结果 (%d 条):\n%s", len(results), formatSearchResults(results))
	logger.Info("搜索完成，共返回 %d 条结果", len(results))

	return response, nil
}

// evaluateMathExpression 简单的数学表达式求值器
func evaluateMathExpression(expr string) (float64, error) {
	// 移除所有空格
	expr = strings.ReplaceAll(expr, " ", "")

	// 简单的递归下降解析器
	result, remaining, err := parseExpression(expr)
	if err != nil {
		return 0, err
	}

	// 确保表达式完全消费
	if remaining != "" {
		return 0, fmt.Errorf("无效的表达式: %s", expr)
	}

	return result, nil
}

// parseExpression 解析数学表达式
func parseExpression(expr string) (float64, string, error) {
	return parseAddition(expr)
}

// parseAddition 解析加法和减法
func parseAddition(expr string) (float64, string, error) {
	result, remaining, err := parseMultiplication(expr)
	if err != nil {
		return 0, "", err
	}

	for {
		if strings.HasPrefix(remaining, "+") {
			right, newRemaining, err := parseMultiplication(remaining[1:])
			if err != nil {
				return 0, "", err
			}
			result += right
			remaining = newRemaining
		} else if strings.HasPrefix(remaining, "-") {
			right, newRemaining, err := parseMultiplication(remaining[1:])
			if err != nil {
				return 0, "", err
			}
			result -= right
			remaining = newRemaining
		} else {
			break
		}
	}

	return result, remaining, nil
}

// parseMultiplication 解析乘法和除法
func parseMultiplication(expr string) (float64, string, error) {
	result, remaining, err := parsePrimary(expr)
	if err != nil {
		return 0, "", err
	}

	for {
		if strings.HasPrefix(remaining, "*") {
			right, newRemaining, err := parsePrimary(remaining[1:])
			if err != nil {
				return 0, "", err
			}
			result *= right
			remaining = newRemaining
		} else if strings.HasPrefix(remaining, "/") {
			right, newRemaining, err := parsePrimary(remaining[1:])
			if err != nil {
				return 0, "", err
			}
			if right == 0 {
				return 0, "", fmt.Errorf("除零错误")
			}
			result /= right
			remaining = newRemaining
		} else {
			break
		}
	}

	return result, remaining, nil
}

// parsePrimary 解析基本元素（数字和括号）
func parsePrimary(expr string) (float64, string, error) {
	if strings.HasPrefix(expr, "(") {
		result, remaining, err := parseExpression(expr[1:])
		if err != nil {
			return 0, "", err
		}
		if !strings.HasPrefix(remaining, ")") {
			return 0, "", fmt.Errorf("缺少右括号")
		}
		return result, remaining[1:], nil
	}

	// 解析数字
	i := 0
	for i < len(expr) && (expr[i] >= '0' && expr[i] <= '9' || expr[i] == '.') {
		i++
	}
	if i == 0 {
		return 0, "", fmt.Errorf("期望数字或左括号")
	}

	numStr := expr[:i]
	num, err := strconv.ParseFloat(numStr, 64)
	if err != nil {
		return 0, "", fmt.Errorf("无效数字: %s", numStr)
	}

	return num, expr[i:], nil
}

// performDuckDuckGoSearch 使用 DuckDuckGo 搜索
func performDuckDuckGoSearch(query string, limit int) ([]SearchResult, error) {
	// DuckDuckGo 即时答案 API
	searchURL := fmt.Sprintf("https://api.duckduckgo.com/?q=%s&format=json&no_html=1&skip_disambig=1",
		url.QueryEscape(query))

	resp, err := http.Get(searchURL)
	if err != nil {
		return nil, fmt.Errorf("搜索请求失败: %v", err)
	}
	defer resp.Body.Close()

	if resp.StatusCode != 200 {
		return nil, fmt.Errorf("搜索API返回错误状态码: %d", resp.StatusCode)
	}

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("读取搜索响应失败: %v", err)
	}

	var searchResponse struct {
		AbstractText     string `json:"AbstractText"`
		AbstractURL      string `json:"AbstractURL"`
		AbstractSource   string `json:"AbstractSource"`
		Answer           string `json:"Answer"`
		AnswerType       string `json:"AnswerType"`
		Definition       string `json:"Definition"`
		DefinitionSource string `json:"DefinitionSource"`
		DefinitionURL    string `json:"DefinitionURL"`
		Heading          string `json:"Heading"`
		RelatedTopics    []struct {
			Text     string `json:"Text"`
			FirstURL string `json:"FirstURL"`
		} `json:"RelatedTopics"`
		Results []struct {
			Text     string `json:"Text"`
			FirstURL string `json:"FirstURL"`
		} `json:"Results"`
	}

	if err := json.Unmarshal(body, &searchResponse); err != nil {
		return nil, fmt.Errorf("解析搜索响应失败: %v", err)
	}

	var results []SearchResult

	// 添加即时答案
	if searchResponse.Answer != "" {
		results = append(results, SearchResult{
			Title:       searchResponse.Heading,
			Description: searchResponse.Answer,
			URL:         "",
		})
	}

	// 添加摘要
	if searchResponse.AbstractText != "" {
		results = append(results, SearchResult{
			Title:       searchResponse.AbstractSource,
			Description: searchResponse.AbstractText,
			URL:         searchResponse.AbstractURL,
		})
	}

	// 添加定义
	if searchResponse.Definition != "" {
		results = append(results, SearchResult{
			Title:       searchResponse.DefinitionSource,
			Description: searchResponse.Definition,
			URL:         searchResponse.DefinitionURL,
		})
	}

	// 添加相关主题
	for _, topic := range searchResponse.RelatedTopics {
		if topic.Text != "" {
			results = append(results, SearchResult{
				Title:       extractTitleFromText(topic.Text),
				Description: topic.Text,
				URL:         topic.FirstURL,
			})
		}
	}

	// 添加结果
	for _, result := range searchResponse.Results {
		if result.Text != "" {
			results = append(results, SearchResult{
				Title:       extractTitleFromText(result.Text),
				Description: result.Text,
				URL:         result.FirstURL,
			})
		}
	}

	// 限制结果数量
	if len(results) > limit {
		results = results[:limit]
	}

	return results, nil
}

// SearchResult 搜索结果结构
type SearchResult struct {
	Title       string
	Description string
	URL         string
}

// formatSearchResults 格式化搜索结果
func formatSearchResults(results []SearchResult) string {
	if len(results) == 0 {
		return "未找到相关结果"
	}

	var formatted strings.Builder
	for i, result := range results {
		formatted.WriteString(fmt.Sprintf("%d. **%s**\n", i+1, result.Title))
		if result.Description != "" {
			// 截断过长的描述
			desc := result.Description
			if len(desc) > 200 {
				desc = desc[:197] + "..."
			}
			formatted.WriteString(fmt.Sprintf("   %s\n", desc))
		}
		if result.URL != "" {
			formatted.WriteString(fmt.Sprintf("   🔗 %s\n", result.URL))
		}
		formatted.WriteString("\n")
	}

	return formatted.String()
}

// extractTitleFromText 从文本中提取标题
func extractTitleFromText(text string) string {
	// 从文本中提取第一行作为标题
	lines := strings.Split(text, "\n")
	if len(lines) > 0 && lines[0] != "" {
		// 移除常见的格式字符
		title := strings.TrimSpace(lines[0])
		title = strings.TrimPrefix(title, "**")
		title = strings.TrimSuffix(title, "**")
		return title
	}
	return "搜索结果"
}
